/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nxlv2.nomad.accessdb.dao.jdbc;

import com.nxlv2.nomad.accessdb.dao.DAOException;
import com.nxlv2.nomad.accessdb.dao.ITvaDao;
import com.nxlv2.nomad.accessdb.dao.IncoherentResultException;
import com.nxlv2.nomad.accessdb.dao.NoResultException;
import com.nxlv2.nomad.businessobjects.Tva;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Nastasia
 */
public class JdbcTvaDao implements ITvaDao{
    
    private static final Logger logger = LoggerFactory.getLogger(JdbcTvaDao.class);
    private static final ConnectionManager manager = new ConnectionManager();

    /**
     * 
     * @param tva
     * @throws DAOException 
     */
    @Override
    public void saveTva(Tva tva) throws DAOException {

         if (null == tva) {
            throw new IllegalArgumentException("Can not save a null object.");
        }

        StringBuilder builder = new StringBuilder();

        builder.append("INSERT INTO tva (idBase, taux, libelle, dateCreation) ");
        builder.append("VALUES (?, ?,AES_ENCRYPT(?,?), NOW() )");

        String request = builder.toString();
        logger.debug("Insert tva: {}", request);

        Connection con = manager.creerConnection();
        PreparedStatement ps;
        try {
            ps = con.prepareStatement(request, PreparedStatement.RETURN_GENERATED_KEYS);
        } catch (SQLException e) {
            logger.error("Can not prepare statement");
            throw new DAOException("Can not prepare statement.", e);
        }

        try {
            ps.setInt(1, tva.getIdBase());
            ps.setDouble(2, tva.getTaux());
            ps.setString(3, tva.getLibelle());
            ps.setString(4, manager.getKeyAES());
            ps.executeUpdate();

        } catch (SQLException e) {
            logger.error("Can not populate request with data.");
            throw new DAOException("Can not populate request with data.", e);
        }

        try {
            ResultSet rs = ps.getGeneratedKeys();

            int pk = 0;

            while (rs.next()) {
                pk = rs.getInt(1);
            }
            tva.setIdAppli(pk);

        } catch (SQLException e) {
            logger.error("Can not execute insert in db.");
            throw new DAOException("Can not execute insert in db.", e);
        }
        manager.fermerConnection();
    }

    /**
     * 
     * @param id
     * @throws DAOException 
     */
    @Override
    public void deleteTva(int id) throws DAOException {
         if (id < 1) {
            throw new IllegalArgumentException("Can not save a null object.");
        }

        StringBuilder builder = new StringBuilder();
        builder.append("DELETE FROM tva WHERE idAppli = ?");

        String request = builder.toString();
        logger.debug("Delete tva: {}", request);

        Connection con = manager.creerConnection();
        PreparedStatement ps;
        try {
            ps = con.prepareStatement(request);
        } catch (SQLException e) {
            logger.error("Can not prepare statement", e);
            throw new DAOException("Can not prepare statement.", e);
        }

        try {
            ps.setInt(1, id);
            ps.executeUpdate();
        } catch (SQLException e) {
            logger.error("Can not delete tva with id.", e);
            throw new DAOException("Can not delete tva with id.", e);
        }
manager.fermerConnection();
    }

    /**
     * 
     * @param tva
     * @throws DAOException 
     */
    @Override
    public void updateTva(Tva tva) throws DAOException {
        if (null == tva) {
            throw new IllegalArgumentException("Can not save a null object.");
        }

        StringBuilder builder = new StringBuilder();
        builder.append("UPDATE tva ");
        builder.append("SET idBase = ?, taux = ?, libelle = AES_ENCRYPT(?,?), dateModification = NOW() ");
        builder.append("WHERE idAppli = ?");

        String request = builder.toString();
        logger.debug("Update tva: {}", request);

        Connection con = manager.creerConnection();
        PreparedStatement ps;
        try {
            ps = con.prepareStatement(request);
        } catch (SQLException e) {
            logger.error("Can not prepare statement");
            throw new DAOException("Can not prepare statement.", e);
        }

        try {
            ps.setInt(1, tva.getIdBase());
            ps.setDouble(2, tva.getTaux());
            ps.setString(3, tva.getLibelle());
            ps.setString(4, manager.getKeyAES());
            ps.setInt(5, tva.getIdAppli());
            ps.executeUpdate();
        } catch (SQLException e) {
            logger.error("Can not populate request with data.");
            throw new DAOException("Can not populate request with data.", e);
        }
        manager.fermerConnection();
    }

    /**
     * 
     * @param id
     * @return Tva
     * @throws DAOException 
     */
    @Override
    public Tva findById(int id) throws DAOException {

        StringBuilder builder = new StringBuilder();
        builder.append("SELECT idAppli, idBase, ");
        builder.append("taux , AES_DECRYPT(libelle,?) AS libelle ");
        builder.append("FROM tva ");
        builder.append("WHERE idAppli = ?");

        String request = builder.toString();
        logger.debug("select tva: {}", request);

        Connection con = manager.creerConnection();
        PreparedStatement ps;
        try {
            ps = con.prepareStatement(request);
        } catch (SQLException e) {
            logger.error("Can not prepare statement");
            throw new DAOException("Can not prepare statement.", e);
        }
        try {
            ps.setString(1, manager.getKeyAES());
            ps.setInt(2, id);
            ps.executeQuery();

        } catch (SQLException e) {
            logger.error("Can not select data with id.");
            throw new DAOException("Can not select data with id.", e);
        }
        ResultSet rst;
        try {
            rst = ps.getResultSet();
        } catch (SQLException e) {
            logger.error("Can not get resultset.");
            throw new DAOException("Can not get resultset.", e);
        }

        List<Tva> tvas = null;
        try {
            tvas = map(rst);
        } catch (SQLException e) {
            logger.error("Can not populate map with result.", e);
            throw new DAOException("Can not populate map with result.", e);
        }

        if (null == tvas || tvas.isEmpty()) {
            throw new NoResultException("No tva found with id " + id);
        }
        if (tvas.size() > 1) {
            throw new IncoherentResultException("Many records with a same id.");
        }
        manager.fermerConnection();
        return tvas.get(0);
    }
    
    /**
     * 
     * @param userId
     * @return List<Tva>
     * @throws DAOException 
     */
    @Override
    public List<Tva> getTvaMaj(int userId) throws DAOException {

        StringBuilder builder = new StringBuilder();
        builder.append("SELECT tva.idAppli, tva.idBase, ");
        builder.append("tva.taux , AES_DECRYPT(tva.libelle,?) AS libelle ");
        builder.append("FROM tva "
                + "JOIN utilisateur u ON u.idAppli = ? ");
        builder.append("WHERE tva.idBase = 0 OR ifnull(tva.idBase,1) OR tva.dateModification > u.dateSynchro ");

        String request = builder.toString();
        logger.debug("select tva: {}", request);

        Connection con = manager.creerConnection();
        PreparedStatement ps;
        try {
            ps = con.prepareStatement(request);
        } catch (SQLException e) {
            logger.error("Can not prepare statement");
            throw new DAOException("Can not prepare statement.", e);
        }
        try {
            ps.setString(1, manager.getKeyAES());
            ps.setInt(2, userId);
            ps.executeQuery();

        } catch (SQLException e) {
            logger.error("Can not select data with id.");
            throw new DAOException("Can not select data with id.", e);
        }
        ResultSet rst;
        try {
            rst = ps.getResultSet();
        } catch (SQLException e) {
            logger.error("Can not get resultset.");
            throw new DAOException("Can not get resultset.", e);
        }

        List<Tva> tvas = null;
        try {
            tvas = map(rst);
        } catch (SQLException e) {
            logger.error("Can not populate map with result.", e);
            throw new DAOException("Can not populate map with result.", e);
        }

        if (null == tvas || tvas.isEmpty()) {
            throw new NoResultException("No tva found with id " + userId);
        }

        manager.fermerConnection();
        return tvas;
    }
    /**
     * 
     * @param rst
     * @return List<Tva>
     * @throws SQLException 
     */
    private List<Tva> map(ResultSet rst) throws SQLException {
        List<Tva> tvas = new ArrayList<>();

        while (rst.next()) {

            Tva tva = new Tva();
            tva.setIdAppli(rst.getInt("idAppli"));
            tva.setIdBase(rst.getInt("idBase"));
            tva.setTaux(rst.getDouble("taux"));
            tva.setLibelle(rst.getString("libelle"));
            tvas.add(tva);
        }
        return tvas;
    }
    
}
